<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Video Stream Client</title>
</head>
<body>
    <h1>WebSocket Video Stream Client</h1>
    <video id="localVideo" autoplay></video>
    <script>
        const localVideo = document.getElementById('localVideo');
        let socket;
        let isSending = true;
        let sendInterval;

        // WebSocket 连接函数
        function connectWebSocket() {
            socket = new WebSocket('ws://1.95.63.100:8080/ws');

            socket.onopen = () => {
                console.log("Connection established successfully.");
                // 成功连接后获取摄像头视频流
                navigator.mediaDevices.getUserMedia({ video: true })
                    .then(stream => {
                        localVideo.srcObject = stream;
                        console.log("Camera stream started.");

                        const videoTrack = stream.getVideoTracks()[0];
                        const videoProcessor = new VideoProcessor(videoTrack);
                        videoProcessor.startSending(socket);
                    })
                    .catch(error => {
                        console.error("Error accessing camera:", error);
                        alert("Failed to access camera: " + error.message);
                    });
            };

            socket.onmessage = (event) => {
                console.log("Received message from server:", event.data);
                // 打印接收到的二进制数据
                if (event.data instanceof Blob) {
                    event.data.arrayBuffer().then(buffer => {
                        const bytes = new Uint8Array(buffer);
                        console.log("Received binary data:", bytes);
                    });
                } else {
                    console.log("Received text data:", event.data);
                }
            };

            socket.onclose = (event) => {
                console.log("Connection closed:", event.reason);
                isSending = false;
                clearInterval(sendInterval);
                // 尝试重新连接
                setTimeout(connectWebSocket, 5000);
            };

            socket.onerror = (error) => {
                console.error("WebSocket Error:", error);
                alert("WebSocket connection error: " + error.message);
                isSending = false;
                clearInterval(sendInterval);
                // 尝试重新连接
                setTimeout(connectWebSocket, 5000);
            };
        }

        // 初始化 WebSocket 连接
        connectWebSocket();

        class VideoProcessor {
            constructor(track) {
                this.track = track;
                this.canvas = document.createElement('canvas');
                this.context = this.canvas.getContext('2d');
            }

            startSending(socket) {
                const frameInterval = 1000 / 5; // 降低帧率到 5 FPS
                sendInterval = setInterval(() => {
                    if (!isSending) return;

                    try {
                        // 降低分辨率
                        const settings = this.track.getSettings();
                        this.canvas.width = settings.width / 2; // 宽度减半
                        this.canvas.height = settings.height / 2; // 高度减半
                        this.context.drawImage(localVideo, 0, 0, this.canvas.width, this.canvas.height);

                        // 转换为 JPEG Blob（二进制格式）
                        this.canvas.toBlob((blob) => {
                            if (isSending && socket.readyState === WebSocket.OPEN) {
                                // 打印发送的二进制数据
                                blob.arrayBuffer().then(buffer => {
                                    const bytes = new Uint8Array(buffer);
                                    console.log("Sending binary data:", bytes);
                                });

                                // 发送二进制数据
                                socket.send(blob);
                                console.log("Sent frame data as binary.");
                            }
                        }, 'image/jpeg', 0.3); // 质量为 0.3
                    } catch (error) {
                        console.error("Error processing video frame:", error);
                    }
                }, frameInterval);
            }
        }
    </script>
</body>
</html>